<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row
      :gutter="16"
      class="mb-6"
      v-hasPermi="['fang:transactionaccount:edit']"
    >
      <el-col :span="6">
        <div class="statistic-card">
          <el-statistic
            :value="statisticsData.currentMonthRentTotal || 0"
            title="本月应收租金"
            :precision="0"
            prefix="¥"
          />
        </div>
      </el-col>
      <el-col :span="6">
        <div class="statistic-card">
          <el-statistic
            :value="statisticsData.currentMonthManagementFee || 0"
            title="本月应收租客管理费"
            :precision="0"
            prefix="¥"
          />
        </div>
      </el-col>
      <el-col :span="6">
        <div class="statistic-card relative">
          <span
            v-if="statisticsData.curMonWaitingRentCount > 0"
            class="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded-full"
          >
            {{ statisticsData.curMonWaitingRentCount }}笔待收
          </span>
          <el-statistic
            :value="convertFenToYuan(statisticsData.curMonWaitingRent || 0)"
            title="本月待收租金"
            :precision="2"
            prefix="¥"
          >
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="statistic-card relative">
          <span
            v-if="statisticsData.curMonWaitingManagementFeeCount > 0"
            class="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded-full"
          >
            {{ statisticsData.curMonWaitingManagementFeeCount }}笔待收
          </span>
          <el-statistic
            :value="
              convertFenToYuan(statisticsData.curMonWaitingManagementFee || 0)
            "
            title="本月待收租客管理费"
            :precision="2"
            prefix="¥"
          >
          </el-statistic>
        </div>
      </el-col>
    </el-row>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="mb-4" @tab-change="handleTabChange">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="逾期租金" name="overdue"></el-tab-pane>
      <el-tab-pane label="已收租金" name="collected"></el-tab-pane>
    </el-tabs>

    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="房源编号" prop="houseNumber">
        <el-input
          v-model="queryParams.houseNumber"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="收款状态" prop="actualStatus">
        <el-select
          v-model="queryParams.actualStatus"
          style="width: 200px"
          filterable
          remote
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in rentStatusList"
            :key="item.id"
            :label="item.lable"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="租客姓名" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="业主" prop="homeownersName">
        <homeowner-selector
          v-model="queryParams.homeownersId"
          width="200px"
          placeholder="请选择"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="success"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['fang:transactionaccount:export']"
          >导出记录</el-button
        >
      </el-form-item>
    </el-form>

    <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->

    <el-table
      v-loading="loading"
      :data="transactionaccountList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="自增ID" align="center" prop="id" v-if="false" />
      <el-table-column
        label="租户合同ID"
        align="center"
        prop="leaseContractId"
        v-if="false"
      />
      <el-table-column
        label="lease_contract_account_period.id"
        align="center"
        prop="leaseContractAccperId"
        v-if="false"
      />

      <el-table-column label="账单编号" align="center" prop="accountNumber" />
      <el-table-column label="房源信息" align="center" prop="address" />
      <el-table-column label="租客信息" align="center">
        <template #default="scope">
          <span>{{ formatTenantInfo(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账期开始" align="center">
        <template #default="scope">
          <span>{{ parseTime(scope.row.ptStartTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账期结束" align="center" prop="">
        <template #default="scope">
          <span>{{ parseTime(scope.row.ptEndTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="应收租金" align="center" prop="tenantRent" />

      <el-table-column
        label="应收租户管理费"
        align="center"
        prop="tenantManagementFee"
      />
      <el-table-column
        label="应收业主管理费"
        align="center"
        prop="homeownersManagementFee"
      />

      <el-table-column label="租客收款状态" align="center" prop="actualStatus">
        <template #default="scope">
          {{ getStatusType(scope.row.actualStatus) }}
        </template>
      </el-table-column>
      <el-table-column
        label="业主收款状态"
        align="center"
        prop="homeownersReceiveStatus"
      >
        <template #default="scope">
          <el-button
            v-if="
              scope.row.actualStatus === TENANT_PAYMENT_STATUS.CONFIRMED &&
              scope.row.homeownersReceiveStatus ===
                HOMEOWNER_RECEIVE_STATUS.UNPAID &&
              checkPermi(['fang:transactionaccount:homeownersconfirm'])
            "
            link
            type="primary"
            @click="handleConfirmPayment(scope.row)"
            >确认收款</el-button
          >
          <span v-else>
            {{ getReceiveStatus(scope.row.homeownersReceiveStatus) }}
            <!-- <span v-if="scope.row.overdueDay > 0 && scope.row.homeownersReceiveStatus === HOMEOWNER_RECEIVE_STATUS.CONFIRMED" class="line-through text-gray-400 ml-1">
              {{ scope.row.overdueDay }}天
            </span> -->
          </span>
        </template>
      </el-table-column>

      <el-table-column label="逾期天数" align="center" prop="overdueDay">
        <template #default="scope">
          <span v-if="scope.row.overdueDay > 0" class="text-red-500"
            >{{ scope.row.overdueDay }}天</span
          >
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleDetail(scope.row)"
            v-hasPermi="['fang:transactionaccount:detail']"
            >详情</el-button
          >
          <el-button
            v-if="
              scope.row.actualStatus === TENANT_PAYMENT_STATUS.PENDING_REVIEW
            "
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fang:transactionaccount:edit']"
            >收款</el-button
          >
          <el-button
            v-else-if="
              scope.row.actualStatus === TENANT_PAYMENT_STATUS.PENDING_VOUCHER
            "
            link
            type="warning"
            @click="handleRemind(scope.row)"
            v-hasPermi="['fang:transactionaccount:remind']"
            >提醒</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改交易帐期对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        ref="transactionaccountRef"
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <el-input v-model="form.leaseContractId" type="hidden" />
        <el-input v-model="form.leaseContractId" type="hidden" />
        <el-input v-model="form.leaseContractAccperId" type="hidden" />

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="账单编号">
              <el-text>{{ form.accountNumber || "-" }}</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账期">
              <span
                >{{ parseTime(form.ptStartTime, "{y}-{m}-{d}") }} ~
                {{ parseTime(form.ptEndTime, "{y}-{m}-{d}") }} (第{{
                  form.accountIndex
                }}期)</span
              >
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item>
              <template #label>
                <span
                  >房租
                  <span class="text-xs text-gray-500"
                    >(应收 ¥{{ formatMoney(form.tenantRent || 0) }})</span
                  ></span
                >
              </template>
              <el-input-number
                v-model="form.actualTenantRent"
                placeholder="请输入租户租金"
                :precision="2"
                :min="0"
                :step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template #label>
                <span
                  >管理费
                  <span class="text-xs text-gray-500"
                    >(应收 ¥{{
                      formatMoney(form.tenantManagementFee || 0)
                    }})</span
                  ></span
                >
              </template>
              <el-input-number
                v-model="form.actualTenantManagementFee"
                placeholder="请输入租户管理费"
                :precision="2"
                :min="0"
                :step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="收款方式">
              <el-select
                v-model="form.paymentType"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in PAYMENT_TYPE_LIST.filter(
                    (item) => item.value !== PAYMENT_TYPE.NONE
                  )"
                  :key="item.value"
                  :label="item.lable"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款日期">
              <el-date-picker
                clearable
                v-model="form.receivePaymentDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择收款日期"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="收款备注">
              <el-input
                type="textarea"
                v-model="form.receiveDesc"
                placeholder="收款相关备注...."
                :rows="4"
                resize="none"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="收款凭证" prop="accountVoucherFile">
              <file-upload v-model="form.voucherFileList" showDownload="true" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button
            v-if="canVoidOrReject"
            type="danger"
            @click="handleVoid"
            v-hasPermi="['fang:transactionaccount:edit']"
            >已作废</el-button
          >
          <el-button
            v-if="canVoidOrReject"
            type="danger"
            @click="handleReject"
            v-hasPermi="['fang:transactionaccount:edit']"
            >不通过</el-button
          >
          <el-button
            type="primary"
            @click="submitForm"
            v-hasPermi="['fang:transactionaccount:tenantconfirm']"
            >确认收款</el-button
          >
        </div>
      </template>
    </el-dialog>

    <tranDtail ref="childDetailRef" />
  </div>
</template>

<script setup name="Transactionaccount">
import {
  listTransactionaccount,
  getTransactionaccount,
  confirmPayment,
  addTransactionaccount,
  updateTransactionaccount,
  getStatistics,
  obsoleteTransactionaccount,
  rejectTransactionaccount,
  tenantConfirmTransactionaccount,
  exportTransactionaccount,
} from "@/api/fang/transactionaccount";
import { convertFenToYuan, convertYuanToFen, getFileObj } from "@/utils/tools";
import { parseTime, blobValidate } from "@/utils/ruoyi";
import { ElLoading } from "element-plus";
import { saveAs } from "file-saver";
import errorCode from "@/utils/errorCode";
import {
  TENANT_PAYMENT_STATUS,
  TENANT_PAYMENT_STATUS_LIST,
  getTenantPaymentStatusText,
  HOMEOWNER_RECEIVE_STATUS,
  getHomeownerReceiveStatusText,
  PAYMENT_TYPE,
  PAYMENT_TYPE_LIST,
} from "@/utils/enums";
import { checkPermi } from "@/utils/permission";
import tranDtail from "./detail.vue";
import HomeownerSelector from "@/components/HomeownerSelector/index.vue";

const { proxy } = getCurrentInstance();

const transactionaccountList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeTab = ref("all");
const statisticsData = ref({
  curMonWaitingManagementFee: 0,
  curMonWaitingManagementFeeCount: 0,
  curMonWaitingRent: 0,
  curMonWaitingRentCount: 0,
  currentMonthManagementFee: 0,
  currentMonthRentTotal: 0,
});

const childDetailRef = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    houseNumber: null,
    actualStatus: null,
    tenantName: null,
    homeownersName: null,
    homeownersId: null,
    searchFlag: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

// 格式化金额显示
const formatMoney = (amount) => {
  if (!amount) return "0.00";
  const yuan = convertFenToYuan(amount);
  return yuan.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

// 格式化数字显示（用于数量）
const formatNumber = (num) => {
  if (!num && num !== 0) return "0";
  return Number(num).toLocaleString("zh-CN");
};

//展示处理
const formatTenantInfo = (row) => {
  const parts = [];
  if (row.tenantName) parts.push(`${row.tenantName}`);
  if (row.tenantPhone) parts.push(`${row.tenantPhone}`);
  return parts.join(" \n ") || "-";
};

// 使用枚举获取租客收款状态文本
const getStatusType = (status) => {
  return getTenantPaymentStatusText(status);
};

// 使用枚举获取业主收款状态文本
const getReceiveStatus = (status) => {
  return getHomeownerReceiveStatusText(status);
};

// 租客收款状态列表（用于下拉框）
const rentStatusList = TENANT_PAYMENT_STATUS_LIST;

// 判断是否可以进行已作废或审核不通过操作
// 只有【待上传凭证、待审核、重新上传】状态才能变更为已作废和审核不通过
const canVoidOrReject = computed(() => {
  const status = form.value.actualStatus;
  return (
    status === TENANT_PAYMENT_STATUS.PENDING_VOUCHER ||
    status === TENANT_PAYMENT_STATUS.PENDING_REVIEW ||
    status === TENANT_PAYMENT_STATUS.REUPLOAD
  );
});

const getOverdueDay = (status) => {
  if (status > 0) {
    return status + "天";
  } else {
    return "-";
  }
};

// 标签页切换
function handleTabChange(tabName) {
  queryParams.value.pageNum = 1;
  // 根据标签页设置searchFlag参数
  if (tabName === "all") {
    // 全部：searchFlag = 1
    queryParams.value.searchFlag = 1;
  } else if (tabName === "overdue") {
    // 逾期租金：searchFlag = 2
    queryParams.value.searchFlag = 2;
  } else if (tabName === "collected") {
    // 已收租金：searchFlag = 3
    queryParams.value.searchFlag = 3;
  }
  getList();
}

// 提醒功能
function handleRemind(row) {
  proxy.$modal
    .confirm("确定要提醒该账单吗?")
    .then(function () {
      // TODO: 调用提醒接口
      proxy.$modal.msgSuccess("提醒已发送");
    })
    .catch(() => {});
}

/** 查询交易帐期列表 */
function getList() {
  loading.value = true;
  listTransactionaccount(queryParams.value).then((response) => {
    transactionaccountList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询统计信息 */
function getStatisticsData() {
  getStatistics()
    .then((response) => {
      if (response.code === 0 && response.data) {
        statisticsData.value = response.data;
      }
    })
    .catch(() => {
      // 静默失败
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    leaseContractId: null,
    leaseContractAccperId: null,
    accountNumber: null,
    tenantRent: null,
    tenantManagementFee: null,
    actualTenantManagementFee: null,
    actualTenantRent: null,
    actualStatus: null,
    homeownersReceiveStatus: null,
    paymentType: null,
    shouldPaymentDate: null,
    receivePaymentDate: null,
    overdueDay: null,
    accountVoucherFile: null,
    voucherFileList: null,
  };
  proxy.resetForm("transactionaccountRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  activeTab.value = "all";
  queryParams.value.searchFlag = 1;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/**
 * 确认收款
 */
function handleConfirmPayment(row) {
  const id = row.id;

  proxy.$modal
    .confirm("确认业主已收款?")
    .then(function () {
      return confirmPayment(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加交易帐期";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getTransactionaccount(_id).then((response) => {
    const data = response.data;
    // 将金额字段从分转换为元（用于表单显示）
    // 将文件列表从接口格式转换为组件格式
    form.value = {
      ...data,
      paymentType: data.paymentType ? data.paymentType : null,
      actualTenantRent: data.actualTenantRent
        ? convertFenToYuan(data.actualTenantRent)
        : null,
      actualTenantManagementFee: data.actualTenantManagementFee
        ? convertFenToYuan(data.actualTenantManagementFee)
        : null,
      voucherFileList: getFileObj(data.voucherFileList),
    };
    open.value = true;
    title.value = "确认收款";
  });
}

/** 详情 */
function handleDetail(row) {
  const _id = row.id || ids.value;
  console.log("1handleDetail");
  childDetailRef.value.openDetail(_id);
}

/** 构建提交数据（公共函数） */
function buildSubmitData() {
  // 将金额字段从元转换为分（用于接口提交），如果为空则传 0
  // 将文件列表从组件格式转换为接口格式（只保留 id, filePath, originalName）
  const voucherFileList =
    form.value.voucherFileList && form.value.voucherFileList.length > 0
      ? form.value.voucherFileList.map((file) => ({
          id: file.id,
          filePath: file.filePath || file.url,
          originalName: file.originalName || file.name,
          fileName: file.originalName || file.name,
        }))
      : [];

  return {
    id: form.value.id || 0,
    leaseContractId: form.value.leaseContractId || 0,
    leaseContractAccperId: form.value.leaseContractAccperId || 0,
    actualTenantRent: form.value.actualTenantRent
      ? convertYuanToFen(form.value.actualTenantRent)
      : 0,
    actualTenantManagementFee: form.value.actualTenantManagementFee
      ? convertYuanToFen(form.value.actualTenantManagementFee)
      : 0,
    paymentType: form.value.paymentType || "",
    receiveDesc: form.value.receiveDesc || "",
    receivePaymentDate: form.value.receivePaymentDate || null,
    voucherFileList: voucherFileList,
  };
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["transactionaccountRef"].validate((valid) => {
    if (valid) {
      const submitData = buildSubmitData();
      // 确认收款使用新的接口
      tenantConfirmTransactionaccount(submitData)
        .then((response) => {
          proxy.$modal.msgSuccess("确认收款成功");
          open.value = false;
          getList();
        })
        .catch(() => {});
    }
  });
}

/** 已作废 */
function handleVoid() {
  if (!form.value.id) {
    proxy.$modal.msgError("请先选择要作废的记录");
    return;
  }
  proxy.$modal
    .confirm("确定要作废该收款记录吗?")
    .then(() => {
      const submitData = buildSubmitData();
      obsoleteTransactionaccount(submitData).then((response) => {
        proxy.$modal.msgSuccess("作废成功");
        open.value = false;
        getList();
      });
    })
    .catch(() => {});
}

/** 不通过 */
function handleReject() {
  if (!form.value.id) {
    proxy.$modal.msgError("请先选择要拒绝的记录");
    return;
  }
  proxy.$modal
    .confirm("确定要不通过该收款记录吗?")
    .then(() => {
      const submitData = buildSubmitData();
      rejectTransactionaccount(submitData).then((response) => {
        proxy.$modal.msgSuccess("操作成功");
        open.value = false;
        getList();
      });
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  if (!ids.value || ids.value.length === 0) {
    proxy.$modal.msgWarning("请先选择要导出的记录");
    return;
  }

  const downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请稍候",
    background: "rgba(0, 0, 0, 0.7)",
  });

  exportTransactionaccount(ids.value)
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        saveAs(blob, `transactionaccount_${new Date().getTime()}.xlsx`);
        proxy.$modal.msgSuccess("导出成功");
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.msg || "导出失败";
        proxy.$modal.msgError(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      proxy.$modal.msgError("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
}

// 初始化 - 设置默认searchFlag为1（全部）
queryParams.value.searchFlag = 1;
getStatisticsData();
getList();
</script>

<style scoped>
.statistic-card {
  height: 100%;
  padding: 20px;
  border-radius: 4px;
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
}

.statistic-card :deep(.el-statistic) {
  --el-statistic-content-font-size: 28px;
}

.statistic-card :deep(.el-statistic__head) {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

.statistic-card :deep(.el-statistic__content) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}
</style>
